var React = require('react');
var _ = require('underscore');
var Dialog = require("../dialog/dialog.jsx");
require('./ext-table.scss');
var ExtTable = React.createClass({
    propTypes: {
        hideIndex: React.PropTypes.array,
        selectList: React.PropTypes.array,
        styleIndex: React.PropTypes.array,
        tableId: React.PropTypes.string,
        dialog: React.PropTypes.bool,
        length: React.PropTypes.number,
        allCheckFlag: React.PropTypes.bool,
        allDisCheckFlag: React.PropTypes.bool,
    },
    getInitialState:function() {
        var {selectList, tableId } = this.props;
        var length = selectList.length;
        return {
            hideIndex: new Array(length),
            styleIndex: new Array(length),
            selectList: selectList,
            tableId: tableId,
            dialog: false,// 显示选择dialog
            length: length,
            allCheckFlag: false,
            allDisCheckFlag: false,
        };

    },
    /**
     * 选择或者取消显示列
     * @param index 需要选择或取消的列
     */
    clickLi(index) {
        var {hideIndex} = this.state;
        hideIndex[index] = !hideIndex[index];
        this.setState({
            hideIndex: hideIndex,
            allCheckFlag: false,
            allDisCheckFlag: false,
        });
    },
    /**
     * 显示对话框
     */
    showSetup() {
        var {styleIndex} = this.state;
        this.setState({
            dialog: true,
            hideIndex: _.extend([], styleIndex),
        });
    },
    /**
     * 关闭对话框
     */
    hideSetup() {
        var {styleIndex} = this.state;
        this.setState({
            dialog: false,
            hideIndex: _.extend([], styleIndex),
        });
    },
    /**
     * 全选，反选
     * @param flag 全选，反选标志
     */
    allClick(flag){
        var {selectList, hideIndex, length} = this.state;
        if(length <= 0){
            return false;
        }
        // 全选
        if(flag){
            for(var i = 0; i < length; i++){
                hideIndex[i] = false;
             }
            this.setState({
                allCheckFlag: true,
                allDisCheckFlag: false,
            });
        }
        // 反选
        if(!flag){
            for(var i = 0; i < length; i++){
                hideIndex[i] = !hideIndex[i];
                // 必选项过滤
                if(selectList[i] && selectList[i].props && selectList[i].props.needShow){
                    hideIndex[i] = false;
                }
            }
            this.setState({
                allDisCheckFlag: true,
                allCheckFlag: false,
            });
        }
        this.setState({
            hideIndex: hideIndex
        });
    },
    /**
     * 保存选择的项
     */
    saveStatus() {
        var {hideIndex}= this.state;
        this.setState({
            styleIndex: hideIndex,
            dialog: false,
        });
    },
    closeDialog() {
        var {styleIndex}= this.state;
        this.setState({
            hideIndex: styleIndex,
            dialog: false,
        });
    },
    render() {
        var {selectList, tableId, hideIndex, dialog, styleIndex, allDisCheckFlag, allCheckFlag } = this.state;
        return(<div>
            <a className="ext-table-buttons button ext-table-a" onClick={this.showSetup}
            style={{marginBottom: '5px', marginTop: '5px'}}>显示设置项</a>
            {
                styleIndex && styleIndex.map((hideI, index) => {
                    var i = index + 1;
                    {/*隐藏此列的th和td*/}
                    var str = '#' + tableId + ' tr th:nth-child(' + i + '){display: none;} '
                        + '#' + tableId + ' tr td:nth-child(' + i + '){display: none;} ';
                    if(!hideI){
                        return null;
                    }
                    return (<style type="text/css"  key={_.uniqueId('ext_style_')}  dangerouslySetInnerHTML={{__html : str}} />);
                })
            }
        {dialog ? <Dialog onClose={this.closeDialog} width="600" title="请设置显示项"
                          onSave={this.saveStatus}>
            <div className="ext-table-all-ctt">
                <span onClick={this.allClick.bind(this, true)} className="ext-checkall ext-check">
                    {allCheckFlag ? <i className="iconfont icon-fangkuangxuanze"></i> : <i className="iconfont  icon-fangkuang"></i> }
                    全选
                </span>
                <span onClick={this.allClick.bind(this, false)} className="ext-checknot ext-check">
                    {allDisCheckFlag ? <i className="iconfont icon-fangkuangxuanze"></i> : <i className="iconfont  icon-fangkuang"></i> }
                    反选
                </span>
            </div>
            <div className="ext-table-select-ctt">
                <ul className="ext-table-select-list">
                    {
                        selectList && selectList.map((obj, index)=>{
                            var { header , needShow} = obj.props;
                            {/*没有header或者必须显示的想不可以隐藏*/}
                            if(!header || needShow){
                                return null;
                            }
                            return (<li onClick={this.clickLi.bind(this, index)}
                                        key={_.uniqueId('ext_li_')} >
                                {hideIndex && hideIndex[index] && !selectList[index].props.needShow ?
                                    <span><i className="iconfont icon-fangkuang"></i>{header}</span>
                                    : <span><i className="iconfont icon-fangkuangxuanze"></i>{header}</span> }
                            </li>);
                        })
                    }
                </ul>
            </div>
            <div style={{textAlign: 'center'}}>
                <button className="button ext-table-buttons" onClick={this.saveStatus}
                        style={{marginRight: '16px'}}>确认</button>
                <button className="button ext-table-buttons" onClick={this.closeDialog} >取消</button>
            </div>
        </Dialog> : null}
        </div>);
    }
});
var GoMeTable = React.createClass({
    renderHtml(){
        var { children, data} = this.props;
        var tableHtml = {tableHeader:[],tableBody:[]};
        /*ɸѡrowHeader��row*/
        var rowHead = _.filter(children,function(obj) {
            return ( obj.props.rowHeader )
        });
        children = _.filter(children,function(obj) {
            return ( !obj.props.rowHeader )
        });
        /*tableͷ*/
        tableHtml.tableHeader.push(
            <tr key={_.uniqueId('thtr_')}>
                {children.map((column)=> {
                    var { header, onHeaderChange, data } = column.props;
                    var Header = header;
                    if (React.isValidElement(header)) {
                        return (<th key={_.uniqueId('th_')}>{header}</th>);
                    }
                    return (<th key={_.uniqueId('th_')}><Header onChange={onHeaderChange} data={data}/></th>);
                })}
            </tr>
        );
        /*tableBody*/
        {data && data.map((item,rowIndex) => {
            var flag = !(rowIndex % 2 === 0);
            if(rowHead[0] && rowHead[0].props.children){//�����rowHeader��ȾrowHeader
                var rowHeadChild = rowHead[0].props.children;
                tableHtml.tableBody.push(
                    <tr className="row-margin" key={_.uniqueId('rh_margin')}>
                        <td colSpan="100"></td>
                    </tr>
                );
                tableHtml.tableBody.push(
                    <tr className="rowHeader" key={_.uniqueId('rh_')}>
                        {rowHeadChild.map((column, index)=> {
                                var { cell, colKey, onClick,className, onCellChange,colSpan, ...others } = column.props;
                                var Cell = cell;
                                if (Cell) {
                                    return (
                                        <td key={_.uniqueId('tdrow_')} colSpan={colSpan}>
                                            <Cell
                                                {...others} data={item} onClick={onClick} colKey={colKey} index={rowIndex}
                                                            onChange={(event) => {onCellChange(event, item,rowIndex);}} />
                                        </td>);
                                }
                                if (colKey == 'INDEX') {
                                    return (<td key={_.uniqueId('tdrow_')} colSpan={colSpan}><span className={className?className:''}>{index + 1}</span></td>);
                                }
                                return (<td key={_.uniqueId('tdrow_')} colSpan={colSpan}><span className={className?className:''}>{item[colKey]}</span></td>);
                            }
                        )}
                    </tr>
                )
            }
            tableHtml.tableBody.push(
                <tr key={_.uniqueId('tr_')} className={flag ? "shadow" : ""}>
                    {children.map((column, index)=> {
                            var { cell, colKey, onClick,className, onCellChange, ...others } = column.props;
                            var Cell = cell;
                            if (Cell) {
                                return (
                                    <td key={_.uniqueId('td_')}>
                                        <Cell
                                            {...others} data={item} onClick={onClick} colKey={colKey} index={rowIndex}
                                                        onChange={(event) => {onCellChange(event, item,rowIndex);}} />
                                    </td>);
                            }
                            if (colKey == 'INDEX') {
                                return (<td key={_.uniqueId('td_')}><span className={className?className:''}>{rowIndex + 1}</span></td>);
                            }
                            return (<td key={_.uniqueId('td_')}><span className={className?className:''}>{item[colKey]}</span></td>);
                        }
                    )}
                </tr>
            );
        })}
        return tableHtml;
    },
    render() {
        var {className, children, id} = this.props;
        var tableHtml = this.renderHtml();
        return (<div className="gome-table-mod">
            <ExtTable selectList={children} tableId={id} />
            <table className={className} id={id}>
                <thead>
                {tableHtml.tableHeader}
                </thead>
                <tbody>
                {tableHtml.tableBody}
                </tbody>
            </table>
        </div>);
    }
});

GoMeTable.Column = React.createClass({
    propTypes: {
        header: React.PropTypes.any,
        colKey: React.PropTypes.string,
        onHeaderChange: React.PropTypes.func,
        onCellChange: React.PropTypes.func,
        data: React.PropTypes.any,
    },
    render() {
        return null;
    }
});

module.exports = GoMeTable;